<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Statement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import = "java.sql.SQLException" %>
<%@ page import = "com.seniorproject.aims.*" %>
<%@ page import = "java.io.File" %>
<%@ page import = "java.io.InputStream" %>
<%@ page import = "java.io.FileInputStream" %>
<%@ page import = "java.util.Properties" %>
<%@ page import = "javax.servlet.ServletContext" %>
<%@ page import = "java.util.List" %>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.regex.Matcher"%>
<%@page import="java.util.regex.Pattern"%>
<%@page import="java.sql.PreparedStatement"%>

<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Employee Edit Name</title>
	
	<link rel="stylesheet" type="text/css" href="css/stylev2.css" />
	<link rel="stylesheet" type="text/css" href="css/frame2.css" />
	
	<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
	
	<style type="text/css">
		a {
	      text-decoration:none;
	   }
	</style>
	
	<script type="text/javascript">
		function change_readonly(tag_id) {
			document.getElementById(tag_id).readOnly = false;
			$('#edit_'+tag_id).remove();
			$('#'+tag_id).focus();
		}
	</script>
</head>
<body>

<%	
	String strUser = String.valueOf(session.getAttribute("sUser"));
	HttpSession htp_session = request.getSession();
			
	// check session
		if (htp_session == null || htp_session.getAttribute("sUser") == null) {
		    // Forward the control to login.jsp if authentication fails or session expires
		    request.getRequestDispatcher("/login.jsp").forward(request,
		        response);
		}
		if(!"admin".equals(htp_session.getAttribute("sUser"))){%>
	 		<script>alert("This user dont have PERMISSION to access this zone.");</script>	 
			<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=system_select.jsp"> 	 
	<%}
		
		String index = request.getParameter("index");	
		String checker = request.getParameter("checker");
		
		System.out.println("employee_index  "+index);//////try//////
		System.out.println("checker:   "+checker);///try///////
		
		if(index==null)
		{
			 response.sendRedirect("admin_employee.jsp");
		}
		
		System.out.println("@ employee_edit_name index:"+index);
			
		//set Database Connection
		String hostProps = "";
		String usernameProps  = "";
		String passwordProps  = "";
		String databaseProps = "";
		
		try {
			//get current path
			ServletContext servletContext = request.getSession().getServletContext();
			
			InputStream input = servletContext.getResourceAsStream("/properties/connectDB.properties");
			Properties props = new Properties();
			
			props.load(input);

			hostProps  = props.getProperty("host");
			usernameProps  = props.getProperty("username");
			passwordProps  = props.getProperty("password");
			databaseProps = props.getProperty("database");
		} catch (Exception e) { 
			out.println(e);  
		}
		
		// connect database
		Connection connect = null;		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		
			connect =  DriverManager.getConnection("jdbc:mysql://" + hostProps  + "/" + databaseProps +
					"?user=" + usernameProps  + "&password=" + passwordProps + "&characterEncoding=tis620" );
		
			if(connect != null){
				System.out.println("Database Connect Sucesses.");
			} else {
				System.out.println("Database Connect Failed.");	
			}

		} catch (Exception e) {
			out.println(e.getMessage());
			e.printStackTrace();
		}
		
		// find name & surname from DB
		People people = new People();
		try{
			ResultSet rs = connect.createStatement().executeQuery("SELECT N.name_th, N.name_en, N.surname_th, N.surname_en, N.index, N.title_th, N.title_en " 
					+ " FROM employee E, full_name N, people P " 
					+ " WHERE P.full_name_id=N.full_name_id AND E.index=P.index"
					+ " AND E.index='"+index+"'");
			
			if(rs.next()) {
				people.setNameTH(rs.getString("name_th"));
				people.setNameEN(rs.getString("name_en"));
				people.setSurnameTH(rs.getString("surname_th"));
				people.setSurnameEN(rs.getString("surname_en"));
				people.setIndex(rs.getString("index"));
				people.setTitleTH(rs.getString("title_th"));
				people.setTitleEN(rs.getString("title_en"));
			}
			
		}catch(Exception a){
			out.println(a.getMessage());
			a.printStackTrace();
			
		}
		
		
		//if add new info do this !	
		if(request.getParameter("checker").equals("ADD")){		
					
			// get value from tag
			String index_new = request.getParameter("index");
			String title_th_new = new String(request.getParameter("title_th").getBytes("ISO8859_1"),"UTF-8");
			String title_en_new = request.getParameter("title_en");
			
			String name_th_old = new String(request.getParameter("name_th_old").getBytes("ISO8859_1"),"UTF-8");
			String surname_th_old = new String(request.getParameter("surname_th_old").getBytes("ISO8859_1"),"UTF-8");
			String name_en_old = request.getParameter("name_en_old");
			String surname_en_old = request.getParameter("surname_en_old");
			
			String name_th_new = new String(request.getParameter("name_th_new").getBytes("ISO8859_1"),"UTF-8");
			String surname_th_new = new String(request.getParameter("surname_th_new").getBytes("ISO8859_1"),"UTF-8");
			String name_en_new = request.getParameter("name_en_new");
			String surname_en_new = request.getParameter("surname_en_new");
			
			System.out.println("name_th_new +++++++++ : "+name_th_new);////////////////////try///////////////////
			System.out.println("surname_th_new: "+surname_th_new);////////////////////try///////////////////
			System.out.println("name_en_new : "+name_en_new);////////////////////try///////////////////
			System.out.println("surname_en_new : "+surname_en_new);////////////////////try///////////////////
			
			Pattern regex = Pattern.compile("[$&+,:;=?@#^*<>|!%]");
			Matcher matchername_th_new = regex.matcher(name_th_new);
			Matcher matchersurname_th_new = regex.matcher(surname_th_new);
			Matcher matchername_en_new = regex.matcher(name_en_new);
			Matcher matchersurname_en_new = regex.matcher(surname_en_new);
			Matcher matchertitle_th_new = regex.matcher(title_th_new);
			Matcher matchertitle_en_new = regex.matcher(title_en_new);
			
			if (matchername_th_new.find() || matchersurname_th_new.find() || matchername_en_new.find() || matchersurname_en_new.find() || matchertitle_th_new.find() || matchertitle_en_new.find()){
			%>
							<script language="javascript"> alert("ข้อมูลไม่ถูกต้อง โปรดใช้ตัวเลขหรือตัวอักษรเท่านั้น");	</script>
			<%}else{
					
				
					// get date
					java.util.Date dt = new java.util.Date();
					java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd",java.util.Locale.US);
					String date_now = sdf.format(dt);
					
					if(!name_th_old.equals(name_th_new) || !surname_th_old.equals(surname_th_new) || !name_en_old.equals(name_en_new) || !surname_en_old.equals(surname_en_new)) {
						try {							
							PreparedStatement pstmt = connect.prepareStatement("INSERT INTO `full_name`(`index`, `title_th`, `title_en`, `name_th`, `name_en`, `surname_th`, `surname_en`, `date`) "
									+ " VALUES ('"+index_new+"', '"+title_th_new+"', '"+title_en_new+"', "
									+ " '"+name_th_new+"', '"+name_en_new+"', '"+surname_th_new+"', '"+surname_en_new+"', '"+date_now+"' ) ", Statement.RETURN_GENERATED_KEYS);
							
							pstmt.executeUpdate();  
							ResultSet keys = pstmt.getGeneratedKeys();    
							keys.next();  
							int key = keys.getInt(1);
							
							String full_name_id = Integer.toString(key);
							System.out.println("full_name_id : "+full_name_id);///////try////////	
							
							String sql = "UPDATE `people` SET full_name_id="+full_name_id+" "
									+ " WHERE `index`='"+index_new+"'";
									
							connect.createStatement().executeUpdate(sql);
							
							/* Log file */						
							String log = "admin edit employee name";
							Log.writeAdminFile(log);
							Log.writeAdminFile(sql);
		
		%>
						<script language="javascript"> alert("บันทึกข้อมูลสำเร็จ");	</script>
						<meta HTTP-EQUIV="Refresh" CONTENT="0; URL=admin_employee.jsp">
						
		<%
					} catch (SQLException e) {
						e.printStackTrace();
		%>
						<script language="javascript"> alert("มีข้อผิดพลาดเกิดขึ้น กรุณาลองใหม่อีกครั้งค่ะ");	</script>
		<%
					}				
					
				}
				else {
					%>
					<script language="javascript"> alert("ข้อมูลไม่มีการเปลี่ยนแปลง กรุณาตรวจสอบอีกครั้งค่ะ");	</script>			
		<%
				}
			}			
		}
		
		connect.close();

%>

	<div id="page-wrap">
		<div id="inside">
			<table border="0">
				<tr style="font-size:24px">
					<td width="600" height="100" style= "background-color: #273b80;border: 0px ;padding: 0px; 0px;" >
						<div id="header_banner-2"></div>
					</td>
					
					<td width="680" height="100" style= "background-color: #273b80;border: 0px;padding: 0px; 0px;" >
						<p align="right"><label><font size="4" color="#ffffff">username : <%=strUser%>&nbsp;&nbsp;</font></label></p>
						<a href="logout.jsp"><p align="right"><label style="cursor: pointer;"><font size="3" color="#ffffff">log out &nbsp;</font></label></p></a>
					</td>
				</tr>
			</table>
	
					<div id="main-content-ac">
						
						<div class="imageFrame">บุคลากร / แก้ไขชื่อ-นามสกุล</div>
						
						<br/><br/><br/><br/><br/>
						
						<center>			
							<table width="800" border="0">
							
								<form method="post" id="form" action="admin_employee_edit_name.jsp">
								
									<input type="hidden" name="checker" id="checker" value="ADD" />
									<input type="hidden" name="index" id="index" value="<%=people.getIndex() %>" />
									<input type="hidden" name="title_th" id="title_th" value="<%=people.getTitleTH() %>" />
									<input type="hidden" name="title_en" id="title_en" value="<%=people.getTitleEN() %>" />
									
					            <tr style="font-size:24px">
						                <td width="400" height="50"><label> <font size="5"><strong>ชื่อเดิม (ภาษาไทย)</strong></font> </label></td>
						                <td width="400">
						                	<input type="hidden" name="name_th_old" id="name_th_old" value="<%=people.getNameTH() %>" />
						                	<input type="text" name="name_th_new" id="name_th_new" style="font-size: 20px;" value="<%=people.getNameTH() %>" readonly="readonly" required/>
						                	<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td>
						                	<center><span title="แก้ไขข้อมูล">
						                		<img src="image/edit_icon.png" id="edit_name_th_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('name_th_new')" />
						                	</span></center>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td height="50"><font size="5"><strong>นามสกุลเดิม (ภาษาไทย)</strong></font></td>
						                <td>
						                	<input type="hidden" name="surname_th_old" id="surname_th_old" value="<%=people.getSurnameTH() %>" />
											<input type="text" name="surname_th_new" id="surname_th_new" style="font-size: 20px;" value="<%=people.getSurnameTH() %>" readonly="readonly" required/>
											<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td>
						                	<center><span title="แก้ไขข้อมูล">
						                		<img src="image/edit_icon.png" id="edit_surname_th_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('surname_th_new')" />
						                	</span></center>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td width="400" height="50"><label> <font size="5"><strong>ชื่อเดิม (ภาษาอังกฤษ)</strong></font> </label></td>
						                <td width="400">
						                	<input type="hidden" name="name_en_old" id="name_en_old" value="<%=people.getNameEN() %>"/>	
						                	<input type="text" name="name_en_new" id="name_en_new" style="font-size: 20px;" value="<%=people.getNameEN() %>" readonly="readonly" required/>
						                	<label><font size="5" color="#FF0000">*</font></label>					                	
						                </td>
						                <td>
						                	<center><span title="แก้ไขข้อมูล">
						                		<img src="image/edit_icon.png" id="edit_name_en_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('name_en_new')" />
						                	</span></center>
						                </td>
						            </tr>
						            
						            <tr style="font-size:24px">
						                <td height="50"><font size="5"><strong>นามสกุลเดิม (ภาษาอังกฤษ)</strong></font></td>
						                <td>
						                	<input type="hidden" name="surname_en_old" id="surname_en_old" value="<%=people.getSurnameEN() %>" />
											<input type="text" name="surname_en_new" id="surname_en_new" style="font-size: 20px;" value="<%=people.getSurnameEN() %>" readonly="readonly" required/>
											<label><font size="5" color="#FF0000">*</font></label>
						                </td>
						                <td>
						                	<center><img src="image/edit_icon.png" id="edit_surname_en_new" style="width: 30px; height: 30px; cursor: pointer;" onclick="change_readonly('surname_en_new')" />
						                	</center>
						                </td>
						            </tr>
					            
					            <tr style="font-size:24px">
					                <td height="50" colspan="3"><label><font size="3" color="#FF0000">หมายเหตุ: * คือ ข้อมูลสำคัญ จำเป็นต้องกรอก</font></label></td>
					            </tr>
					            					    
					            <tr style="font-size:24px">
					                <td height="50">
					                    <center><input type="submit" name="save" id="save" value="save" class="buttonStyle" style=""/></center>
					                </td>
					       </form>
					                <td>
					                  <a href="admin_employee.jsp"><button class="buttonStyle">ยกเลิก</button></a>
					              </td>
					              <td>
						          </td>
					            </tr>
					      </table>
					      </center>
					      
					      <br/><br/><br/>
				
			<div style="clear: both;"></div>
				
			<div id="footer"></div>
			
		</div>		
			<div style="clear: both;"></div>		
   </div>

</body>
</html>